package com.laiketui.order.common;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLock {
    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_PREFIX = "lock:";

    /**
     * 阻塞方式获取锁
     * @param key
     * @param expireTime
     * @return
     */
    public RLock lock(String key){
        //可重入锁
        RLock lock = redissonClient.getLock(LOCK_PREFIX + key);
        //lock.lock(expireTime, TimeUnit.SECONDS); //阻塞方式获取锁，设置过期时间
        lock.lock();
        return lock;
    }


    /**
     * 非阻塞方式获取锁
     * @param key
     */
    public Boolean tryLock(String key){
        try {
            RLock lock = redissonClient.getLock(LOCK_PREFIX + key);

            return lock.tryLock(5L, TimeUnit.SECONDS); //非阻塞方式获取锁,设置在指定时间内失败重试获取锁
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 非阻塞方式获取锁
     * @param key key
     * @param expireTime 指定持有时间
     */
    public Boolean tryLock(String key,Integer expireTime){
        try {
            RLock lock = redissonClient.getLock(LOCK_PREFIX + key);

            //非阻塞方式获取锁,设置在指定时间内失败重试获取锁
            return lock.tryLock(5L,expireTime,TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 释放锁
     * @param key
     */
    public void unlock(String key) {
        RLock lock = redissonClient.getLock(LOCK_PREFIX+key);
        if (lock.isLocked()) {
            lock.unlock();
        }
    }
}

